#ifndef _BASE_SIMPLE_DB_POOL_
#define _BASE_SIMPLE_DB_POOL_

#include <mysql++/mysql++.h>
#include <boost/thread.hpp>

namespace base {

class SimpleMysqlThreadInvoker {
public:
  SimpleMysqlThreadInvoker() {
    mysqlpp::Connection::thread_start();
  }

  ~SimpleMysqlThreadInvoker() {
    mysqlpp::Connection::thread_end();
  }
};


// 注意，多线程模式时，需要在线程运行时候，先调用mysql_thread_init(), 线程结束时候，
// 调用 mysql_thread_stop(). 
// 例如，可以封装线程对象，确保线程run/stop的时候, 调用相应的API.
class SimpleConnectionPool : public mysqlpp::ConnectionPool {
public:
  SimpleConnectionPool(const char * db, const char * server, const char * user, const char * password) :
    conns_in_use_(0),
    db_(db),
    server_(server),
    user_(user),
    password_(password) {
  }

  ~SimpleConnectionPool();

  mysqlpp::Connection* grab();

  void release(const mysqlpp::Connection* pc);

protected:
  mysqlpp::Connection* create();

  void destroy(mysqlpp::Connection* cp);

  unsigned int max_idle_time();

private:
  boost::mutex mutex_;

  unsigned int conns_in_use_;
  std::string db_, server_, user_, password_;
};

}

#endif //_BASE_SIMPLE_DB_POOL_
